package flex.cc.store.api;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import flex.cc.PublicUtil;
import flex.cc.basicinformation.dao.ValueAddedServiceProviderDao;
import flex.cc.basicinformation.entity.ValueAddedServiceProviderEntity;
import flex.cc.common.utils.DateUtil;
import flex.cc.core.support.BaseController;
import flex.cc.store.service.StorePushService;
import flex.cc.store.util.PushDecryptUtil;
import flex.cc.util.APIConfigUtil;

/**
 * 
 * @author WANGCONG
 * 2021年12月20日下午13:05:17
 * @desc 网点推送对接接口
 */
@RestController
@RequestMapping(value = "/storeapi")
public class StorePushController extends BaseController{

	@Resource
	private StorePushService storePushService;
	@Resource
    private ValueAddedServiceProviderDao valueAddedserviceProviderDao;
    @Autowired
    private APIConfigUtil apiConfigUtil;
	
	/**
	 * 
	 * @author WANGCONG
	 * 2021年12月20日下午13:05:36
	 * @desc 网点推送入口
	 */
	@SuppressWarnings("rawtypes")
	@ResponseBody
    @RequestMapping("/shopInfoPush")
    public JSONObject shopInfoPush(HttpServletRequest request) throws Exception{
		JSONObject jsonResult = new JSONObject();
		String resultCode = "SUCCESS";
		String resultDes = "成功,系统处理正常";
		long startTime = System.currentTimeMillis();
    	logger.info("StorePushController 网点推送接口:begintime=" + DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
		try {
			request.setCharacterEncoding("UTF-8"); //设置编码
            String requestJson = IOUtils.toString(request.getInputStream(), "UTF-8"); //读取请求报文
            logger.info("StorePushController 网点推送接口:reqJson=" + requestJson);
            if (requestJson != null && !"".equals(requestJson)) {
            	JSONObject jsonObject = JSONObject.parseObject(requestJson);
            	Map requestMap = jsonObject.toJavaObject(Map.class);
                if (PublicUtil.isNotEmpty(requestMap.get("encryptJsonStr"))) {
                	String encryptJsonStr = (String)requestMap.get("encryptJsonStr");
                	String apiCode = (String)requestMap.get("apiCode"); //约束之后新服务商要传的唯一识别码
                	apiCode = PublicUtil.isNotEmpty(apiCode) ? apiCode.trim() : "SD";//为空，默认盛大
                	String provider = "";
                	String temp_status = "";
                    List<ValueAddedServiceProviderEntity> serviceProviderList = valueAddedserviceProviderDao.queryProviderList();
                    for (int i = 0; i < serviceProviderList.size(); i++) {
            			ValueAddedServiceProviderEntity serviceProviderEntity = serviceProviderList.get(i);
                    	String providerCode = serviceProviderEntity.getApiCode();
                    	if(providerCode!=null && apiCode.equals(providerCode)){
//                    		provider = String.valueOf(serviceProviderEntity.getId());
                    		provider = serviceProviderEntity.getDataId();
                    		temp_status = serviceProviderEntity.getStatus(); //状态：0-禁用，1-启用（默认）
                    		break;
                    	}
            		}
            		if(PublicUtil.isEmpty(provider)){
                    	resultCode = "ERROR";
            			resultDes = "服务商apiCode信息配置有误，请联系运营人员";
                    	logger.error("StorePushController 网点推送接口失败:服务商apiCode信息配置有误，请联系运营人员");
                    }else{
                    	if( temp_status!=null && "0".equals(temp_status) ){
                    		resultCode = "ERROR";
                			resultDes = "服务商信息未启用，请联系运营人员";
                			logger.error("StorePushController 网点推送接口失败:服务商信息未启用，请联系运营人员");
                    	}else{
                    		String storeSourceKey = apiConfigUtil.getApiConfig(provider, "store_decode");
                    		String key3Des = apiConfigUtil.getApiConfig(provider, "store_key3Des");
                    		if(PublicUtil.isNotEmpty(apiCode)){
                            	requestJson = PushDecryptUtil.jiemi(encryptJsonStr,storeSourceKey,key3Des); //解密
                    		}
                        	storePushService.saveShop(requestJson);
                    	}
                	}
                }else{
                	resultCode = "ERROR";
                	resultDes = "接口处理异常:请求报文为空";
                	logger.error("StorePushController 网点推送接口---处理异常:请求报文为空");
                }
            }else {
            	resultCode = "ERROR";
            	resultDes = "接口处理异常:请求报文为空";
            	logger.error("StorePushController 网点推送接口---处理异常:请求报文为空");
            }
		} catch (Exception e) {
			resultCode = "ERROR";
			resultDes = "数据处理异常";
        	logger.error("StorePushController 网点推送接口异常:" + e.getMessage());
		}
		jsonResult.put("resultCode", resultCode);
		jsonResult.put("resultDes", resultDes);
		long endTime = System.currentTimeMillis();
        logger.info("StorePushController 网点推送接口:endtime="+DateUtil.getStrDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS")+"; 处理时长="+(endTime - startTime)+"; resJson="+jsonResult.toString());
		return jsonResult;
	}
	
}
